package com.yudean.erp.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.reflection.SunUnsafeReflectionProvider;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.yudean.erp.converter.NullConverter;
import com.yudean.erp.entity.IdsPmProTech;

import java.util.List;

public class XmlUtil {

    private static XStream xStream = null;
    static {
        xStream = new XStream(new StaxDriver());
        //开启注解配置（别名通过注解在Entity中进行配置）
        xStream.autodetectAnnotations(true);
        xStream.allowTypesByRegExp(new String[] { ".*" });
        NullConverter nullConverter = new NullConverter(xStream.getMapper(),new SunUnsafeReflectionProvider());
        // 将转换器注册到非常低的位置非常重要
        xStream.registerConverter(nullConverter,XStream.PRIORITY_VERY_LOW);
        // 不输出class信息
        xStream.aliasSystemAttribute(null, "class");
        //别名配置
        //xStream.alias("IdsPmProTech", IdsPmProTech.class);
        xStream.alias("data", IdsPmProTech.class);
        xStream.alias("datalist", List.class);

    }

    /**
     * Bean --> XML
     * @param obj   Entity
     * @return String XML字符串
     */
    public static String bean2Xml(Object obj){
        xStream.processAnnotations(obj.getClass());
        return xStream.toXML(obj);
    }

    /**
     * XML ——> Bean
     * @param xml 字符串
     * @return  obj Entity
     */
    public static <T> T parseFromXml(String xml,Class<T> clazz){
        xStream.processAnnotations(clazz);
        return (T)xStream.fromXML(xml);
    }

}
